//
//  RHAuthViewController.swift
//  微博新浪
//
//  Created by hezerong on 16/6/9.
//  Copyright © 2016年 Rocky. All rights reserved.
//

import UIKit

class RHAuthViewController: UIViewController {
    
    lazy var cancelBarButtonItem :UIBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "cancel")
    
   lazy var webView = UIWebView()
    
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        loadwebView()
        
        
        setUpUI()
        
    }

    
  

}

// Mark  设置UI
extension RHAuthViewController{

    func setUpUI(){
    
       self.navigationItem.leftBarButtonItem = cancelBarButtonItem
    }
}

extension RHAuthViewController:UIWebViewDelegate{

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        print("\(request.URL?.absoluteString)")
        
        
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(directURL) {
        
        
//            print(request.URL?.query)
            
            
            if let query = request.URL?.query  where query.hasPrefix("code="){
            
            let startIndex = query.rangeOfString("code=")?.endIndex
            let code = query.substringFromIndex(startIndex!)
//            print(code)
                
                //调用loadaccessToken业务来获取accesToKen
                
                RHNetWorkTool.sharedTool.loadAccesstoken(code, callBack: { (response) -> () in
                   
                    //如果获取accessToken 正确返回了数据：
                    if let accessTokenDic = response {
                        //使用access_token 请求登录帐号信息
                        RHNetWorkTool.sharedTool.loadUserAccount(accessTokenDic["access_token"] as! String,
                            uid: accessTokenDic["uid"] as! String,
                            callBack: { (response) -> () in
                                //如果获取登录帐号信息，正确返回了数据：
                                if var userDic = response {
                                    
                                    //将userDic 和 accessTokenDic 合并
                                    for (key, value) in accessTokenDic {
                                        userDic[key] = value
                                    }
                                    
                                    //合并成功之后，保存用户信息
                                    UserAccount.sharedUserAccunt.saveUserAccount(userDic)
                                    
                                    //向展示的页面发送用户授权成功的通知
                                    let authSuscessNotification = NSNotification(name: oauthSuccessNotification, object: nil)
                                    NSNotificationCenter.defaultCenter().postNotification(authSuscessNotification)
                                    self.dismissViewControllerAnimated(true, completion: nil)
                                }
                        })
                    }

                    
                    
                })
            
            }
        }
        
        return true
    }
    
    ///  webView加载完成后调用
    ///
    ///  - parameter webView: 当前的webview
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //TODO:这是一段测试用的代码
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'hezerongandy@sina.com';document.getElementById('passwd').value = 'f526265799he'")
    }

}

extension RHAuthViewController{
  
    func loadwebView(){
      
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=125408973&redirect_uri=https://www.baidu.com"
        
        let url = NSURL(string: urlStr)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
        
    
    }

}

extension RHAuthViewController{

    func cancel(){
        
            delay(1.2) { () -> () in
                
                self.dismissViewControllerAnimated(true, completion: nil)

            }
      


        }
    
    
}